package com.yc.thread;

import java.util.ArrayList;
import java.util.List;

public class Demo5 {
	
	List<Object> store = new ArrayList<>();
	
	public synchronized void producer() throws InterruptedException {
		while(true) {
			if(store.isEmpty()) {
				for (int i = 0; i < 10; i++) {
					Object o = "商品" + i;
					store.add(o);
					System.out.println(Thread.currentThread().getName() + " 生产了 " + o);
					Thread.sleep(200);
				}
			}
			// 先通知其他线程
			this.notify();
			// 开始等待
			this.wait();
		}
	}
	
	public synchronized void comsumer() throws InterruptedException {
		while(true) {
			if(!store.isEmpty()) {
				Object o = store.remove(0);
				System.out.println(Thread.currentThread().getName() + " 消费了 " + o);
				Thread.sleep(100);
			} else {
				// 先通知其他线程
				this.notify();
				// 开始等待
				this.wait();
			}
		}
	}
	
	public static void main(String[] args) {
		
		Demo5 d = new Demo5();
		
		new Thread(()->{
			try {
				d.producer();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}).start();
		
		new Thread(()->{
			try {
				d.comsumer();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}).start();
		
		
	}

}
